<!-- 菜单管理 -->
<template>
  <n-space vertical>
    <n-form ref="formRef" label-placement="left" label-width="auto" require-mark-placement="right-hanging" size="medium" inline>
      <n-form-item label="状态" path="inputValue">
        <n-input v-model:value="listQurey.status" placeholder="请选择" />
      </n-form-item>
      <n-form-item label="菜单名称" path="inputValue">
        <n-input v-model:value="listQurey.name" placeholder="请输入菜单名称" />
      </n-form-item>
      <n-button type="info" @click="handleAdd">新增</n-button>
    </n-form>
    <n-grid x-gap="20" :cols="5">
      <n-grid-item>
        <n-card class="tree-card">
          <n-tree
            show-line
            block-line
            :data="treeData"
            :default-expanded-keys="defaultExpandedKeys"
            key-field="key"
            label-field="label"
            children-field="children"
            selectable
            :node-props="nodeProps"
            :accordion="true"
          />
        </n-card>
      </n-grid-item>
      <n-grid-item :span="4">
        <n-card>
          <n-space vertical>
            <n-data-table :bordered="false" :single-line="false" :columns="columns" :data="tableData" :loading="listLoading" />
            <n-space>
              <n-pagination :item-count="tableTotal" :page-sizes="[10, 20, 30, 40]" show-size-picker>
                <template #prefix="{ itemCount }">共 {{ itemCount }} 条</template>
              </n-pagination>
            </n-space>
          </n-space>
        </n-card>
      </n-grid-item>
    </n-grid>
    <n-modal
      v-model:show="showModal"
      preset="dialog"
      :show-icon="false"
      :auto-focus="false"
      title="Dialog"
      :mask-closable="false"
      :closable="false"
      style="width: 50%"
    >
      <template #header>
        <div>{{ modalTitle }}</div>
      </template>
      <n-form ref="formRef" label-placement="left" label-width="100" :model="formData" :rules="modelRules" :disabled="modalType === 'look'">
        <n-form-item label="父级菜单名称" path="parentName">
          <n-input v-model:value="formData.parentName" placeholder="顶级菜单" disabled />
        </n-form-item>
        <n-form-item label="名称" path="name">
          <n-input v-model:value="formData.name" placeholder="请选择" />
        </n-form-item>
        <n-form-item label="编码" path="code">
          <n-input v-model:value="formData.code" placeholder="请选择" />
        </n-form-item>
        <n-form-item label="链接" path="router">
          <n-input v-model:value="formData.router" placeholder="/或/#/后的路径如：/basic/menu，父级菜单填/basic" />
        </n-form-item>
        <n-form-item label="组件名称" path="componentName">
          <n-input v-model:value="formData.componentName" placeholder="路由组件的名称，请勿重复" />
        </n-form-item>
        <n-form-item label="组件路径" path="component">
          <n-input v-model:value="formData.component" placeholder="@/views下的路径如：/basic/menu，父级菜单填Layout" />
        </n-form-item>
        <n-form-item label="排序" path="sort">
          <n-input-number v-model:value="formData.sort" :min="1" style="width: 100%" />
        </n-form-item>
        <n-form-item label="菜单图标" path="icon">
          <n-input v-model:value="formData.icon" placeholder="仅一级菜单填写图标名" />
        </n-form-item>
        <n-form-item label="路由类型" path="type">
          <n-radio-group v-model:value="formData.type" name="radiogroup">
            <n-space>
              <n-radio :value="0">节点</n-radio>
              <n-radio :value="1" disabled>功能</n-radio>
              <n-radio :value="2" disabled>按钮</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-radio-group v-model:value="formData.status" name="radiogroup">
            <n-space>
              <n-radio :value="1">启用</n-radio>
              <n-radio :value="0">停用</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>
      </n-form>
      <template #action>
        <n-button @click="modalCancel">取消</n-button>
        <n-button type="error" @click="modalConfirm" v-if="modalType !== 'look'">确定</n-button>
      </template>
    </n-modal>
  </n-space>
</template>

<script lang="ts" setup>
  import { h, ref } from 'vue'
  import { repeat } from 'seemly'
  import {
    NSpace,
    NForm,
    NFormItem,
    NInput,
    NCard,
    NTree,
    NGrid,
    NGridItem,
    NButton,
    NDataTable,
    NModal,
    NInputNumber,
    NRadioGroup,
    NRadio,
    NPopconfirm,
    NPagination
  } from 'naive-ui'
  import type { FormInst, FormRules, TreeOption, DataTableColumns } from 'naive-ui'

  const formRef = ref<FormInst | null>(null)
  const listLoading = ref(false)
  const tableData = ref([])
  const listQurey = ref({ status: null, name: null })
  const showModal = ref(false)
  const modalTitle = ref('')
  const modalType = ref('')
  const formData = ref({
    no: null,
    name: null,
    code: null,
    router: null,
    component: null,
    componentName: null,
    icon: null,
    sort: null,
    status: 1,
    parentCode: 0,
    parentName: null,
    type: 0
  })
  const modelRules: FormRules = {
    name: { required: true, message: '请输入名称', trigger: 'blur' },
    router: { required: true, message: '请输入路由地址', trigger: 'blur' },
    component: { required: true, message: '请输入组件路径', trigger: 'blur' },
    componentName: {
      required: true,
      message: '请输入组件名称',
      trigger: 'blur'
    },
    sort: {
      required: true,
      type: 'number',
      message: '请输入排序',
      trigger: 'blur'
    }
  }

  function modalConfirm(e: MouseEvent) {
    e.preventDefault()
    formRef.value?.validate((errors) => {
      if (!errors) {
        console.log(errors)
      } else {
        console.log(errors)
      }
    })
  }
  function modalCancel() {
    showModal.value = false
    // 重置表单
    formData.value = {
      no: null,
      name: null,
      code: null,
      router: null,
      component: null,
      componentName: null,
      icon: null,
      sort: null,
      status: 1,
      parentCode: 0,
      parentName: null,
      type: 0
    }
  }
  //点击节点的方法
  const nodeProps = ({ option }: any) => {
    return {
      onClick() {
        console.log(option.key) //拿到点击节点的数据
        search()
      }
    }
  }

  function createTreeData(level = 4, baseKey = ''): TreeOption[] | undefined {
    if (!level) return undefined
    return repeat(5 - level, undefined).map((_, index) => {
      const key = `${baseKey}${level}${index}`
      return {
        label: createLabel(level),
        key: key,
        children: createTreeData(level - 1, key)
      }
    })
  }

  function createLabel(level: number): string {
    if (level === 4) return '菜单'
    if (level === 3) return '一生二'
    if (level === 2) return '二生三'
    if (level === 1) return '三生万物'
    return ''
  }

  const treeData = createTreeData()
  console.log('data', treeData)
  const defaultExpandedKeys = ref(['40', '41'])

  // 新增
  function handleAdd() {
    showModal.value = true
    modalTitle.value = '新增'
    modalType.value = 'add'
  }

  // 获取表格数据
  search()
  function search() {
    listLoading.value = true
    tableData.value = createTableData() as any
    setTimeout(() => {
      listLoading.value = false
    }, 1000)
  }

  interface RowData {
    no: number
    name: string
    router: string
    componentName: string
    component: string
    icon: string
    status: number
  }
  function createTableData(): RowData[] {
    return [
      {
        no: 0,
        name: 'John Brown',
        router: '32',
        componentName: 'New York No. 1 Lake Park',
        component: 'sss',
        icon: '',
        status: 1
      },
      {
        no: 1,
        name: 'Jim Green',
        router: '42',
        componentName: 'London No. 1 Lake Park',
        component: 'sss',
        icon: '',
        status: 0
      },
      {
        no: 2,
        name: 'Joe Black',
        router: '32',
        componentName: 'Sidney No. 1 Lake Park',
        component: 'sss',
        icon: '',
        status: 1
      }
    ]
  }

  function createColumns({
    handleInfo,
    handleEdit,
    handleChangeStatus,
    handleDelete
  }: {
    handleInfo: (rowData: RowData) => void
    handleEdit: (rowData: RowData) => void
    handleChangeStatus: (rowData: RowData) => void
    handleDelete: (rowData: RowData) => void
  }): DataTableColumns<RowData> {
    return [
      {
        title: '名称',
        key: 'name'
      },
      {
        title: '路由',
        key: 'router'
      },
      {
        title: '组件名称',
        key: 'componentName'
      },
      {
        title: '组件路径',
        key: 'component'
      },
      {
        title: '菜单图标',
        key: 'icon'
      },
      {
        title: '状态',
        key: 'status',
        render(row) {
          return row.status === 1 ? '启用' : '停用'
        }
      },
      {
        width: 250,
        title: '操作',
        key: 'actions',
        render(row) {
          return h(NSpace, null, {
            default: () => [
              h(
                NButton,
                {
                  quaternary: true,
                  type: 'default',
                  size: 'tiny',
                  onClick: () => void handleInfo(row)
                },
                { default: () => '查看' }
              ),
              h(
                NButton,
                {
                  quaternary: true,
                  type: 'info',
                  size: 'tiny',
                  onClick: () => void handleEdit(row)
                },
                { default: () => '编辑' }
              ),
              h(
                NPopconfirm,
                {
                  onPositiveClick: () => {
                    handleChangeStatus(row)
                  }
                },
                {
                  trigger: () =>
                    h(
                      NButton,
                      {
                        quaternary: true,
                        type: row.status === 1 ? 'error' : 'success',
                        size: 'tiny'
                      },
                      { default: () => (row.status === 1 ? '停用' : '启用') }
                    ),
                  default: () => `确认要'${row.status === 1 ? '停用' : '启用'}'该条数据吗？`
                }
              ),
              h(
                NPopconfirm,
                {
                  onPositiveClick: () => {
                    handleDelete(row)
                  }
                },
                {
                  trigger: () =>
                    h(
                      NButton,
                      {
                        quaternary: true,
                        type: 'error',
                        size: 'tiny'
                      },
                      { default: () => '删除' }
                    ),
                  default: () => `确认要'删除'该条数据吗？`
                }
              )
            ]
          })
        }
      }
    ]
  }
  const columns = createColumns({
    // 查看
    handleInfo(rowData: any) {
      showModal.value = true
      modalTitle.value = '查看'
      modalType.value = 'look'
      formData.value = rowData
    },
    // 编辑
    handleEdit(rowData: any) {
      showModal.value = true
      modalTitle.value = '编辑'
      modalType.value = 'edit'
      formData.value = rowData
    },
    // 停启用状态
    handleChangeStatus(rowData) {},
    // 删除
    handleDelete(rowData) {
      console.log('删除')
    }
  })
  const tableTotal = tableData.value.length
</script>

<style lang="less" scoped>
  .tree-card {
    min-height: 750px;
  }
</style>
